package com.cltech.frame.transformer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.BlobType;
import org.hibernate.type.descriptor.java.DataHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.convert.JodaTimeConverters;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.StringUtils;

import java.beans.PropertyDescriptor;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * beanTransformerAdapter.
 *
 * @param <T> DTO
 * @author guanbo
 * @version 1.0.0.0
 */

public class BeanTransformerAdapter<T> implements ResultTransformer {
    /**
     * defaultConversionService.
     */
    private static DefaultConversionService conversionService;

    static {
        BeanTransformerAdapter.conversionService = new DefaultConversionService();
        final Collection<Converter<?, ?>> convertersToRegister = JodaTimeConverters.getConvertersToRegister();
        for (Converter<?, ?> converter : convertersToRegister) {
            BeanTransformerAdapter.conversionService.addConverter(converter);
        }
        BeanTransformerAdapter.conversionService.addConverter(ClobToStringConverter.INSTANCE);
        BeanTransformerAdapter.conversionService.addConverter(BlobToStringConverter.INSTANCE);
    }

    /**
     * Logger available to subclasses.
     */
    private final Log logger = LogFactory.getLog(getClass());

    /**
     * The class we are mapping to.
     */
    private Class<T> mappedClass;


    /**
     * Whether we're strictly validating.
     */
    private boolean checkFullyPopulated = false;

    /**
     * Whether we're defaulting primitives when mapping a null value.
     */
    private boolean primitivesDefaultedForNullValue = false;

    /**
     * Map of the fields we provide mapping for.
     */
    private Map<String, PropertyDescriptor> mappedFields;

    /**
     * Set of bean properties we provide mapping for.
     */
    private Set<String> mappedProperties;

    /**
     * Create a new BeanPropertyRowMapper for bean-style configuration.
     *
     * @see #setMappedClass
     * @see #setCheckFullyPopulated
     */
    public BeanTransformerAdapter() {

    }

    /**
     * Create a new BeanPropertyRowMapper, accepting unpopulated properties
     * in the target bean.
     * <p>Consider using the {@link #newInstance} factory method instead,
     * which allows for specifying the mapped type once only.
     *
     * @param mappedClass the class that each row should be mapped to
     */
    public BeanTransformerAdapter(final Class<T> mappedClass) {
        initialize(mappedClass);
    }


    /**
     * Create a new BeanPropertyRowMapper.
     *
     * @param mappedClass         the class that each row should be mapped to
     * @param checkFullyPopulated whether we're strictly validating that
     *                            all bean properties have been mapped from corresponding database fields
     */
    public BeanTransformerAdapter(final Class<T> mappedClass, final boolean checkFullyPopulated) {
        initialize(mappedClass);
        this.checkFullyPopulated = checkFullyPopulated;
    }

    /**
     * Static factory method to create a new BeanPropertyRowMapper
     * (with the mapped class specified only once).
     *
     * @param mappedClass the class that each row should be mapped to
     * @param <T>         class type
     * @return instance
     */
    public static <T> BeanPropertyRowMapper<T> newInstance(final Class<T> mappedClass) {
        final BeanPropertyRowMapper<T> newInstance = new BeanPropertyRowMapper<T>();
        newInstance.setMappedClass(mappedClass);
        return newInstance;
    }

    /**
     * Initialize the mapping metadata for the given class.
     *
     * @param mappedClass the mapped class.
     */
    protected void initialize(final Class<T> mappedClass) {
        this.mappedClass = mappedClass;
        this.mappedFields = new HashMap<String, PropertyDescriptor>();
        this.mappedProperties = new HashSet<String>();
        final PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
        for (PropertyDescriptor pd : pds) {
            this.mappedFields.put(pd.getName().toLowerCase(), pd);
            final String underscoredName = underscoreName(pd.getName());
            if (!pd.getName().toLowerCase().equals(underscoredName)) {
                this.mappedFields.put(underscoredName, pd);
            }
            this.mappedProperties.add(pd.getName());
        }
    }

    /**
     * Convert a name in camelCase to an underscored name in lower case.
     * Any upper case letters are converted to lower case with a preceding underscore.
     *
     * @param name the string containing original name
     * @return the converted name
     */
    private String underscoreName(final String name) {
        if (!StringUtils.hasLength(name)) {
            return "";
        }
        final StringBuilder result = new StringBuilder();
        result.append(name.substring(0, 1).toLowerCase());
        for (int i = 1; i < name.length(); i++) {
            final String s = name.substring(i, i + 1);
            final String slc = s.toLowerCase();
            if (!s.equals(slc)) {
                result.append("_").append(slc);
            } else {
                result.append(s);
            }
        }
        return result.toString();
    }

    /**
     * Get the class that we are mapping to.
     *
     * @return mapped class
     */
    public final Class<T> getMappedClass() {
        return this.mappedClass;
    }

    /**
     * Set the class that each row should be mapped to.
     *
     * @param mappedClass mapped class
     */
    public void setMappedClass(final Class<T> mappedClass) {
        if (this.mappedClass == null) {
            initialize(mappedClass);
        } else {
            if (!this.mappedClass.equals(mappedClass)) {
                throw new InvalidDataAccessApiUsageException("The mapped class can not be reassigned to map to "
                        + mappedClass + " since it is already providing mapping for " + this.mappedClass);
            }
        }
    }

    /**
     * Return whether we're strictly validating that all bean properties have been
     * mapped from corresponding database fields.
     *
     * @return flag
     */
    public boolean isCheckFullyPopulated() {
        return this.checkFullyPopulated;
    }


    /**
     * Set whether we're strictly validating that all bean properties have been
     * mapped from corresponding database fields.
     * <p>Default is {@code false}, accepting unpopulated properties in the
     * target bean.
     *
     * @param checkFullyPopulated checkFullyPopulated
     */
    public void setCheckFullyPopulated(final boolean checkFullyPopulated) {
        this.checkFullyPopulated = checkFullyPopulated;
    }


    /**
     * Return whether we're defaulting Java primitives in the case of mapping a null value
     * from corresponding database fields.
     *
     * @return boolean
     */
    public boolean isPrimitivesDefaultedForNullValue() {
        return primitivesDefaultedForNullValue;
    }

    /**
     * Set whether we're defaulting Java primitives in the case of mapping a null value
     * from corresponding database fields.
     * <p>Default is {@code false}, throwing an exception when nulls are mapped to Java primitives.
     *
     * @param primitivesDefaultedForNullValue primitivesDefaultedForNullValue
     */
    public void setPrimitivesDefaultedForNullValue(final boolean primitivesDefaultedForNullValue) {
        this.primitivesDefaultedForNullValue = primitivesDefaultedForNullValue;
    }

    /**
     * Initialize the given BeanWrapper to be used for row mapping.
     * To be called for each row.
     * <p>The default implementation is empty. Can be overridden in subclasses.
     *
     * @param bw the BeanWrapper to initialize
     */
    protected void initBeanWrapper(final BeanWrapper bw) {
        bw.setConversionService(conversionService);
    }

    /**
     * Retrieve a JDBC object value for the specified column.
     * <p>The default implementation calls
     * {@link JdbcUtils#getResultSetValue(ResultSet, int, Class)}.
     * Subclasses may override this to check specific value types upfront,
     * or to post-process values return from {@code getResultSetValue}.
     *
     * @param rs    is the ResultSet holding the data
     * @param index is the column index
     * @param pd    the bean property that each result object is expected to match
     *              (or {@code null} if none specified)
     * @return the Object value
     * @throws SQLException in case of extraction failure
     * @see JdbcUtils#getResultSetValue(ResultSet, int, Class)
     */
    protected Object getColumnValue(final ResultSet rs, final int index, final PropertyDescriptor pd) throws
            SQLException {
        return JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
    }

    @Override
    public Object transformTuple(final Object[] tuple, final String[] aliases) {
        final T mappedObject = BeanUtils.instantiateClass(this.mappedClass);
        final BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
        initBeanWrapper(bw);
        //when tuple is BaseClass，copy tuple'properties to mappedObject'properties ,and only excue once .
        int copyPropertiesTimes = 0;
        final Set<String> populatedProperties = isCheckFullyPopulated() ? new HashSet<String>() : null;
        if (!aliasesIsEmpty(aliases)) {
            for (int i = 0; i < aliases.length; i++) {
                final Object value = tuple[i];
                if(null == value){
                    final String column = aliases[i];
                    setValue(mappedObject, column, value, populatedProperties, bw);
                    continue;
                }
                Class clazz = value.getClass();
                //基本类型作为属性处理.
                if (isBaseClass(clazz)) {
                    final String column = aliases[i];
                    setValue(mappedObject, column, value, populatedProperties, bw);
                }else{
                    final String column = aliases[i];
                    final PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
                    if(null==pd){
                        if(copyPropertiesTimes==0){
                            BeanUtils.copyProperties(value, mappedObject);
                            copyPropertiesTimes++;
                        }else{
                            throw new DataRetrievalFailureException("when use JpaQL select ,Data Transfer Object "
                                    + "property must match aliase");
                        }
                    }else{
                        setValue(mappedObject, column, value, populatedProperties, bw);
                    }
                }
            }
            if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
                throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                        + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
            }
        } else {
            if(tuple.length>1){
                throw new DataRetrievalFailureException("Use JpaQL select com.bidding.entity's property must add aliase");
            }else{
                final Object value = tuple[0];
                Class clazz = value.getClass();
                if (!isBaseClass(clazz)) {
                    BeanUtils.copyProperties(value, mappedObject);
                } else {
                    throw new DataRetrievalFailureException("Use JpaQL select com.bidding.entity's property must add aliase");
                }
            }
        }
        return mappedObject;
    }
    private void setValue(final T mappedObject, final String column, final Object value,  final Set<String>
            populatedProperties, final BeanWrapper bw) {
        final PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
        if (pd != null) {
            try {
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (final TypeMismatchException e) {
                    if (value == null && primitivesDefaultedForNullValue) {
                        logger.debug("Intercepted TypeMismatchException for column " + column + " and" +
                                " column '"
                                + column + "' with value " + value + " when setting property '" + pd
                                .getName()
                                + "' of type " + pd.getPropertyType()
                                + " on object: " + mappedObject);
                    } else {
                        throw e;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (final NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException("Unable to map column " + column
                        + " to property " + pd.getName(), ex);
            }
        }
    }
    private boolean isBaseClass(final Class clazz) {
        if (clazz.isPrimitive() || Number.class.isAssignableFrom(clazz) || clazz.isPrimitive()
                || String.class.isAssignableFrom(clazz) || Date.class.isAssignableFrom(clazz)) {
            return true;
        }
        return false;
    }

    private boolean aliasesIsEmpty(final String[] aliases) {
        for (int i = 0; i < aliases.length; i++) {
            final String column = aliases[i];
            if (StringUtils.isEmpty(column)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List transformList(final List list) {
        return list;
    }

    /**
     * clob converter to String.
     */
    enum ClobToStringConverter implements Converter<Clob, String> {
        /**
         * INSTANCE.
         */
        INSTANCE;

        @Override
        public String convert(final Clob source) {
            return DataHelper.extractString(source);
        }
    }

    /**
     * blob converter to String.
     */
    enum BlobToStringConverter implements Converter<Blob, String> {
        /**
         * INSTANCE.
         */
        INSTANCE;

        @Override
        public String convert(final Blob source) {
            return BlobType.INSTANCE.toString(source);
        }
    }
}
